package com.example.bilibili_miaosha.controller;

import com.example.bilibili_miaosha.entity.User;
import com.example.bilibili_miaosha.service.IGoodsService;
import com.example.bilibili_miaosha.service.impl.UserServiceImpl;
import com.example.bilibili_miaosha.vo.DetailVo;
import com.example.bilibili_miaosha.vo.GoodsVO;
import com.example.bilibili_miaosha.vo.RespBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName GoodController
 * @Description 商品类控制
 * @Author 川
 * @Date 2022/3/29 15:36
 * @Version 1.0
 **/
@Controller
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;


    /**
     * @Description: 接受地址为/goods/toList的请求，跳转到goodList.html页面
     * @Param: [session, model, ticket] 从request中获取session，cookie，   model从源代码来看就像一个包含各种属性的容器
     * @return: java.lang.String
     * @Author: 弓川
     * @Date: 2022/3/29
     **/
/*

    @RequestMapping("/toList")//因为这里接受的是页面请求，那么下面这些参数都是从request中获取的
    public String toList(Model model, HttpServletRequest request, HttpServletResponse response) {
//        if (ticket ==null){//如果没有登录直接跳转到登录界面
//            return "login";
//        }
////        User user = (User) session.getAttribute(ticket);//从session中拿到这个用户（原始版本的cookies登录方法）
//        User user = userService.getUserByCookie(ticket, request, response);
//        if (user == null) {
//            return "login";
//        }
        model.addAttribute("goodsList", goodsService.findGoodsVo());
        return "goodList";
    }
*/
    /**
    * @Description: 进行页面缓存优化，将toList保存在redis里面
    * @Param:
    * @return:
    * @Author: 弓川
    * @Date: 2022/4/11
    **/
    @RequestMapping(value = "/toList",produces = "text/html;charset=utf-8")//因为这里接受的是页面请求那么下面这些参数都是从request中获取的
    @ResponseBody
    public String toList(Model model,User user, HttpServletRequest request, HttpServletResponse response) {
        ValueOperations valueOperations = redisTemplate.opsForValue();

        //Redis中获取页面
        String html = (String)valueOperations.get("goodList");
        if (StringUtils.hasText(html)) {
            return html;
        }
        model.addAttribute("user",user);
        model.addAttribute( "goodsList", goodsService.findGoodsVo());
        //如果没有获取到页面
        //手动渲染
        WebContext webContext = new WebContext(request,response,request.getServletContext()
                ,request.getLocale(), model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process("goodList",webContext);//这个goodList对应这thymleaf中的模板
        if (StringUtils.hasText(html)){
            valueOperations.set("goodList",html,30, TimeUnit.SECONDS);
        }
        return html;
    }


    /*@RequestMapping(value = "/toDetail2/{goodsId}",produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toDetail(Model model, User user,
                           HttpServletRequest request, HttpServletResponse response, @PathVariable Long goodsId) {

        ValueOperations valueOperations = redisTemplate.opsForValue();
        //Redis中获取页面
        String html = (String)valueOperations.get("goodsDetail:"+goodsId);
        if (StringUtils.hasText(html)) {
            return html;
        }

        GoodsVO goodsVo = goodsService.findGoodsVoByGoodsId(goodsId);
        Date startDate = goodsVo.getStartDate();
        Date endDate = goodsVo.getEndDate();
        Date nowDate = new Date();
        //秒杀状态
        int secKillStatus = 0;
        //秒杀倒计时
        int remainSeconds = 0;
        //秒杀还未开始
        if (nowDate.before(startDate)) {
            remainSeconds = ((int) ((startDate.getTime() - nowDate.getTime()) / 1000));
        } else if (nowDate.after(endDate)) {
            //	秒杀已结束
            secKillStatus = 2;
            remainSeconds = -1;
        } else {
            //秒杀中
            secKillStatus = 1;
            remainSeconds = 0;
        }
        model.addAttribute("remainSeconds", remainSeconds);
        model.addAttribute("secKillStatus", secKillStatus);
        model.addAttribute("goods", goodsVo);
        model.addAttribute("user",user);
        //如果没有页面的话，需要进行手动渲染
        WebContext webContext = new WebContext(request, response,
                request.getServletContext(), request.getLocale(), model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process("goodsDetail",webContext);
        if (html != null) {
            valueOperations.set("goodsDetail:"+goodsId,html,60,TimeUnit.SECONDS);
        }
        return html;
    }
    */

    /**
    * @Description: 将商品详情页静态化存储，优化服务
    * @Param:
    * @return:
    * @Author: 弓川
    * @Date: 2022/4/13
    **/
    @RequestMapping("/detail/{goodsId}")
    @ResponseBody
    public RespBean toDetail(User user, @PathVariable Long goodsId) {
        GoodsVO goodsVo = goodsService.findGoodsVoByGoodsId(goodsId);
        Date startDate = goodsVo.getStartDate();
        Date endDate = goodsVo.getEndDate();
        System.out.println(goodsVo.toString());
        Date nowDate = new Date();
        //秒杀状态
        int secKillStatus = 0;
        //秒杀倒计时
        int remainSeconds = 0;
        //秒杀还未开始
        if (nowDate.before(startDate)) {
            remainSeconds = ((int) ((startDate.getTime() - nowDate.getTime()) / 1000));
        } else if (nowDate.after(endDate)) {
            //	秒杀已结束
            secKillStatus = 2;
            remainSeconds = -1;
        } else {
            //秒杀中
            secKillStatus = 1;
            remainSeconds = 0;
        }

        DetailVo detailVo = new DetailVo();
        detailVo.setUser(user);
        detailVo.setGoodsVO(goodsVo);
        detailVo.setSeckillStatus(secKillStatus);
        detailVo.setRemainSeconds(remainSeconds);


        return RespBean.success(detailVo);
    }
}
